package com.techfort.testguice;

import java.io.IOException;
import java.util.List;


import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
import android.content.Context;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.techfort.testguice.db.BookmarkDAO;
import com.techfort.testguice.db.FavouriteDAO;
import com.techfort.testguice.pojo.Bookmark;
import com.techfort.testguice.pojo.Favourite;
import com.techfort.tfal.rss.Message;
import com.techfort.tfal.rss.RssDomParser;


public class Player extends RoboActivity {
	
	private MediaPlayer player;
	@InjectView(R.id.playpause) Button play;
	@InjectView(R.id.next) Button next;
	@InjectView(R.id.rewind) Button prev;
	@InjectView(R.id.time) TextView time;
	@InjectView(R.id.progressbar) SeekBar pb;
	@InjectView(R.id.duration) TextView duration;
	@InjectView(R.id.title) TextView title;
	private Handler titleHandler;
	private int currentPosition;
	private List<Message> messages;
	private FavouriteDAO fdao;
	private BookmarkDAO bmdao;
	private String rssurl;
	
	public void onCreate(Bundle bundle){
		
		super.onCreate(bundle);
		setContentView(R.layout.player);
		Bundle extra = this.getIntent().getExtras();
		currentPosition = 0;
		player = new MediaPlayer();
		
		rssurl = extra.getString("rssurl");
		
		fdao = new FavouriteDAO(this);
		bmdao = new BookmarkDAO(this);
		title.setText(rssurl);
		if(time==null){
			Log.i("INFO","NO time textview found");
		}
		time.setText("");
		ListView list = (ListView) findViewById(R.id.chapters_list);
		play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				playOrPause();
			}
		});
		
		next.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				currentPosition = (currentPosition + 1) % messages.size();
				setMp3(currentPosition);
			}
		});
		
		prev.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				currentPosition-=1;
				if(currentPosition==-1) { 
					currentPosition = messages.size() -1; 
				} else {
					currentPosition = currentPosition % messages.size();
				}
				setMp3(currentPosition);
			}
		});
		
		//pb = (SeekBar) findViewById(R.id.progressbar);
		
		pb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if(fromUser){
					player.seekTo(progress);
				}
			}
		});
		
		
		RssDomParser parser = new RssDomParser(rssurl);
		messages = parser.parse();
		
		
		MesageAdapter adapter = new MesageAdapter(this, R.layout.chapter, messages);
		list.setAdapter(adapter);
		
		titleHandler = new Handler(){
			@Override
			public void handleMessage(android.os.Message msg) {
				time.setText(formatMillisec(player.getCurrentPosition()));
			}
		};
		
		
		try {
			setMp3(0);
			Runnable updateProgress = new Runnable() {
				
				@Override
				public void run() {
					while(true){
						try {
			                   if(player.isPlaying()) {
			                       Thread.sleep(500);
			                       pb.setProgress(player.getCurrentPosition());
			                       //android.os.Message msg = titleHandler.obtainMessage(); 
			                       //titleHandler.sendMessage(msg);
			                       titleHandler.sendEmptyMessage(0);
			                   }
			               } catch (java.lang.InterruptedException e) {
			                   
			               }
					}
				}
			};
			
			Thread t = new Thread(updateProgress);
			t.start();
			
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	
	private String formatMillisec(int duration){
		int time = duration / 1000; 
		int secs = (int)(time % 60);
		String seconds = (secs < 10) ? "0" + Integer.toString(secs) : Integer.toString(secs);
		String minutes = Integer.toString((int)((time % 3600) / 60));
		return minutes + ":" + seconds;
		
	}
	
	private void setMp3(int position) {
		try {
			player.stop();
			player.reset();
			currentPosition = position;
			player.setDataSource(messages.get(position).getLink().toString());
			title.setText(messages.get(position).getTitle());
			player.prepare();
			pb.setProgress(0);
			pb.setMax(player.getDuration());
			player.start();
			
			duration.setText(formatMillisec(player.getDuration()));
		} catch(IllegalStateException e){
			
		} catch(IllegalArgumentException e){
			
		} catch(IOException e){
			
		}
 	}
	
	private void playOrPause(){
		Log.i("INFO","PlayPause");
		if(player!=null){
			if(player.isPlaying()){
				player.pause();
			} else {
				player.start();
			}
		}
	}

	
	
	private class MesageAdapter extends ArrayAdapter<Message>{

		private List<Message> items;
		public MesageAdapter(Context context, int textViewResourceId,
				List<Message> objects) {
			super(context, textViewResourceId, objects);
			items = objects;
			
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			final int pos = position;
			if(v==null){
				LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.chapter, null);
			}
			Message message = items.get(position);
			ImageView image = (ImageView) v.findViewById(R.id.icon);
			TextView tv = (TextView) v.findViewById(R.id.chaptername);
			
			image.setImageDrawable(Player.this.getResources().getDrawable(R.drawable.icon));
			tv.setText(message.getTitle());
			if(position%2==0) { v.setBackgroundColor(Color.WHITE); }
			v.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					try {
						setMp3(pos);
						
					} catch (IllegalArgumentException e) {
						
						e.printStackTrace();
					} catch (IllegalStateException e) {
						
						e.printStackTrace();
					} 
				}
			});
			return v;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.favmenu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()){
		case R.id.add_bm:
			Bookmark bm = new Bookmark(rssurl,player.getCurrentPosition());
			bmdao.store(bm);
			Toast.makeText(this, "Bookmark added", 3000);
		case R.id.add_fav:
			fdao.store(new Favourite(rssurl));
			Toast.makeText(this, "Favourite added", 3000);
		}
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		
		try {
			bmdao.close();
			fdao.close();
		} catch(Exception e){
			
		}
		super.onDestroy();
	}
}
